package cn.itcast.interceptor;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.itcast.util.CookieUtil;
import cn.itcast.util.OutputStringController;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * 自定义token拦截器
 * @author 辉
 *
 */
public class TokenInterceptor implements HandlerInterceptor {

	@Resource
    OutputStringController osc;
	@Resource
    CookieUtil cookieUtil;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		response.setCharacterEncoding("UTF-8");
		//String token = request.getHeader("JSESSIONID");
		Cookie[] cookies = request.getCookies();
		//cookie中的token
		String token = "";
		//cookie中的sessionId
		String sessionId = "";
		if(StringUtils.isNotBlank(ObjectUtils.toString(cookies))) {
			for (Cookie cookie : cookies) {
			    switch(cookie.getName()){
			        case "token":
			            token = cookie.getValue();
			            break;
			        case "JSESSIONID":
			        	sessionId = cookie.getValue();
			            break;
			        default:
			            break;
			    }
			}
		}
		
		System.out.println("cookie中的token:"+token);
		System.out.println("cookie中的sessionId:"+sessionId);
		//token不存在
		if(null != token && !token.equals("")) {
			//验证token是否正确
			String tk = (String) request.getSession().getAttribute("token");
			System.out.println("sessio中的token:"+tk);
			if(tk!=null && tk.equals(token)) {
				CookieUtil.addCookie(response, "token", token, 1800);
				return true;
			}
		}

		response.getWriter().write("认证失败");
		return false;
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

}
